// [\u4e00-\u9fa5] 中文验证规则
import validate from 'wechat-validate'
Page({
  behaviors: [validate],
  data: {
    point: '',
    building: '',
    room: '',
    name: '',
    gender: 1,
    mobile: '',
    idcardFrontUrl: '',
    idcardBackUrl: '',
  },
  async onLoad({ point, building, room, id }) {
    console.log(point, building, room, id)
    if (id) {
      const { data, code } = await wx.http.get('/room/' + id)

      if (code !== 10000) return wx.utils.toast('参数错误')
      this.setData(data)
    } else {
      this.setData({
        point,
        building,
        room,
      })
    }
    wx.setNavigationBarTitle({
      title: id ? '修改房屋信息' : '添加房屋信息',
    })
  },
  // 校验规则
  rules: {
    name: [
      { required: true, message: '请填写姓名!' },
      { pattern: /^[\u4e00-\u9fa5]{2,5}$/, message: '请填写2-5位中文字符!' },
    ],
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请检查手机号码是否正确!' },
    ],
    idcardFrontUrl: [{ required: true, message: '请上传身份证照片面' }],
    idcardBackUrl: [{ required: true, message: '请上传身份证国徽面' }],
  },
  // 上传图片
  async uploadPicture(ev) {
    // 区分上传的是人像还是国徽面
    console.log(ev.mark.type)
    const type = ev.mark.type
    const media = await wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed'],
    })
    // 真正上传接口
    wx.uploadFile({
      filePath: media.tempFiles[0].tempFilePath,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: 'Bearer ' + getApp().token,
      },
      success: (result) => {
        console.log(result.data)
        const data = JSON.parse(result.data)
        console.log(data)
        this.setData({
          [type]: data.data.url,
        })
      },
    })
  },
  // 提交
  async goList() {
    console.log(this.validate())
    // 校验数据
    if (!this.validate()) return
    // 这一步操作是为了把调接口不需要的数据给剔除 获得一个只为调接口的数据
    // eslint-disable-next-line no-unused-vars
    const { __webviewId__, status, ...data } = this.data
    const { code } = await wx.http.post('/room', data)
    if (code !== 10000) return wx.utils.toast('提交数据失败')
    // 回退路由，delta的配置是n就回退n步路由
    wx.navigateBack({
      delta: this.data.id ? 2 : 4,
    })
  },
  removePicture(ev) {
    // 移除图片的类型（身份证正面或反面）
    const type = ev.mark.type
    this.setData({ [type]: '' })
  },
})
